<template>
  <div class="container">
    <div class="titleBoxOut">
      <div class="titleBox clearfix">
        <span class="blockTitle">用户管理</span>
        <el-button
          type="primary"
          round
          class="listAddBtn fr"
          @click="addAccount"
          v-show="
            this.$store.state.buttonLimitsArr.indexOf('userManage:add') > -1
          "
          >新增用户</el-button
        >
      </div>
    </div>
    <div class="centerSection">
      <el-row class="searchBox searchInputWidth">
        <el-form :inline="true" :model="filterField">
          <el-form-item label="用户名" class="row-padding-bottom">
            <el-input
              placeholder="请输入"
              clearable
              v-model="filterField.username"
              @blur="filterField.username = changeValue($event)"
            ></el-input>
          </el-form-item>
          <el-form-item label="姓名" class="row-padding-bottom">
            <el-input
              placeholder="请输入"
              clearable
              v-model="filterField.nickname"
              @blur="filterField.nickname = changeValue($event)"
            ></el-input>
          </el-form-item>
          <el-form-item label="状态" class="row-padding-bottom">
            <el-select
              v-model="filterField.enabled"
              placeholder="请选择"
              clearable
            >
              <el-option label="启用" value="true"></el-option>
              <el-option label="禁用" value="false"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button
              type="primary"
              icon="icon iconfont iconchazhao1"
              @click="searchTable"
              class="commonBtn"
            ></el-button>
          </el-form-item>
        </el-form>
      </el-row>
      <!-- 列表 -->
      <el-table
        :data="tableData"
        :header-cell-style="{ background: '#eef1f6', color: '#606266' }"
        highlight-current-row
        stripe
        v-loading="loading"
        style="border: 1px solid #dfe6ec"
      >
        <el-table-column
          align="center"
          prop="username"
          label="用户名"
          :formatter="formatTd"
        ></el-table-column>
        <el-table-column
          align="center"
          prop="nickname"
          label="姓名"
          :formatter="formatTd"
        ></el-table-column>
        <el-table-column
          align="center"
          prop="phone"
          label="手机号"
          :formatter="formatTd"
        ></el-table-column>
        <el-table-column
          align="center"
          prop="deptmentName"
          label="部门名称"
          :formatter="formatTd"
        ></el-table-column>
        <el-table-column
          align="center"
          prop="enabled"
          label="状态"
          :formatter="formatState"
        ></el-table-column>
        <el-table-column align="left" label="操作" width="200px" fixed="right">
          <template slot-scope="scope">
            <!-- //修改
              hasUserUpdate:false,
              //分配角色
              hasUserroleUpdate:false,
              //启用，禁用
              hasUserstatusUpdate:false -->
            <div
              v-if="hasUserUpdate || hasUserroleUpdate || hasUserstatusUpdate"
            >
              <el-link
                type="primary"
                @click="handleEdit(scope.$index, scope.row)"
                v-show="hasUserUpdate"
                >修改</el-link
              >
              <el-link
                type="primary"
                style="margin: 0 10px"
                @click="assigningRoles(scope.$index, scope.row)"
                v-show="hasUserroleUpdate"
                >分配角色</el-link
              >
              <el-link
                type="primary"
                @click="toForbidRow(scope.$index, scope.row)"
                v-show="hasUserstatusUpdate"
              >
                {{ scope.row.enabled == true ? '禁用' : '启用' }}
              </el-link>
            </div>
            <div v-else>
              <span>--</span>
            </div>
          </template>
        </el-table-column>
        <!-- 表格数据为空时，页面显示 -->
        <div slot="empty" v-show="isShow">
          <emptyTable emptyText="暂无相关信息"></emptyTable>
        </div>
      </el-table>
      <!-- filterField为搜索条件 -->
      <Pagination
        ref="pagination"
        @getList="getTableList"
        :filterField="filterField"
        :requestUrl="requestUrl"
      ></Pagination>
    </div>
    <!--新增编辑界面-->
    <el-dialog
      :title="addOrEdit == 0 ? '新建用户' : '编辑用户'"
      :visible.sync="formVisible"
      :close-on-click-modal="false"
      @close="handleCloseRules"
      width="840px"
      custom-class="brand-dialog-min-width"
      :modal-append-to-body="false"
    >
      <el-form
        :model="formData"
        label-width="80px"
        :rules="formRules"
        ref="formData"
      >
        <el-row class="row-padding-bottom">
          <el-col :span="12">
            <el-form-item label="姓名" prop="nickname">
              <el-input
                v-model="formData.nickname"
                autocomplete="off"
                placeholder="请输入"
                @blur="formData.nickname = changeValue($event)"
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="手机号" prop="tel">
              <el-input
                v-model="formData.tel"
                placeholder="用于账号修改和找回密码"
                @blur="formData.tel = changeValue($event)"
              ></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row class="row-padding-bottom">
          <el-col :span="12">
            <el-form-item label="用户名" prop="username">
              <el-input
                v-model="formData.username"
                placeholder="建议使用姓名拼音+数字"
                @blur="formData.username = changeValue($event)"
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="账号密码">
              账号初始密码默认为手机号后6位
            </el-form-item>
          </el-col>
        </el-row>
        <el-row class="row-padding-bottom">
          <el-col :span="12">
            <el-form-item label="部门名称" prop="deptmentName">
              <el-input
                v-model="formData.deptmentName"
                placeholder="请输入部门名称"
                @blur="formData.deptmentName = changeValue($event)"
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="用户类型" prop="type">
              <el-select
                v-model="formData.type"
                clearable
                filterable
                placeholder="请选择"
              >
                <el-option
                  v-for="(item, index) of typeData"
                  :key="index"
                  :label="item.name"
                  :value="item.code"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row class="row-padding-bottom">
          <el-col :span="12">
            <el-form-item label="管辖区域" prop="areaId">
              <el-cascader
                v-model="areaId"
                :options="areasOptions"
                :props="{ checkStrictly: true }"
                @change="handleChange"
                clearable
              ></el-cascader>
            </el-form-item>
          </el-col>
          <el-col :span="12" v-show="formData.type != 'MONITOR'">
            <el-form-item label="管辖行业" prop="industryId">
              <el-select
                v-model="formData.industryId"
                clearable
                filterable
                placeholder="请选择"
              >
                <el-option
                  v-for="(item, index) of industryData"
                  :key="index"
                  :label="item.name"
                  :value="item.code"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click.native="handleClose" class="cancel">取消</el-button>
        <el-button
          type="primary"
          @click.native="toAddSubmit"
          class="save"
          :loading="isUserLoading"
          >提交</el-button
        >
      </div>
    </el-dialog>
    <el-dialog
      title="分配角色"
      :visible.sync="roluFormVisible"
      :close-on-click-modal="false"
      custom-class="dialog-minwidth"
      :modal-append-to-body="false"
    >
      <el-form
        :model="roluFormData"
        label-width="80px"
        :rules="roluFormRules"
        ref="roluFormData"
      >
        <el-row class="row-padding-bottom">
          <el-form-item label="角色" prop="role">
            <el-checkbox-group v-model="role" @change="handleChecked">
              <el-checkbox
                :label="item.id"
                v-for="(item, index) of roleList"
                :key="index"
                >{{ item.name }}</el-checkbox
              >
            </el-checkbox-group>
          </el-form-item>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click.native="closeRoluDialog" class="cancel"
          >取消</el-button
        >
        <el-button
          type="primary"
          @click.native="toSaveRolu"
          class="save"
          :loading="isRuleLoading"
          >提交</el-button
        >
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { mapState, mapActions } from 'vuex'
export default {
  name: 'userManage',
  components: {},
  data() {
    var checkRole = (rule, value, callback) => {
      var that = this

      if (that.role.length == 0) {
        return callback(new Error('请选择角色'))
      } else {
        callback()
      }
    }
    var checkArea = (rule, value, callback) => {
      var that = this
      // console.log(that.areaId)
      if (that.areaId.length < 1) {
        return callback(new Error('请选择管辖区域'))
      } else {
        callback()
      }
    }
    var checkIndustryId = (rule, value, callback) => {
      var that = this
      // console.log(that.areaId)
      if (that.formData.type == 'MONITOR') {
        callback()
        // return callback(new Error('请选择管辖区域'));
      } else {
        if (!that.formData.industryId) {
          return callback(new Error('请选择管辖行业'))
        } else {
          callback()
        }
      }
    }
    return {
      requestUrl: 'api-u/users/userlist', //表格请求路径
      createTime: [],
      areaOptions: [], //区域
      tableData: [], //表格数据
      filterField: {
        username: '',
        nickname: '',
        enabled: '',
      },
      // 添加编辑弹窗
      formVisible: false,
      addOrEdit: 0,
      formData: {
        nickname: '',
        tel: '',
        username: '',
        deptmentName: '',
        areaId: '',
        industryId: '',
        type: '',
      }, //新增编辑界面数据
      areaId: '',
      formRules: {
        nickname: [
          {
            required: true,
            message: '请输入姓名',
            trigger: 'blur',
          },
        ],
        tel: [
          {
            required: true,
            pattern: /^1[3456789]\d{9}$/,
            message: '手机号格式错误',
            trigger: 'blur',
          },
        ],
        username: [
          {
            required: true,
            message: '用户名为6-18位字母、数字、下划线_组合，不能是纯数字',
            pattern: /(?![0-9]+$)[0-9a-zA-Z_]{6,18}/,
            trigger: 'blur',
          },
        ],
        deptmentName: [
          {
            required: true,
            message: '请输入部门名称',
            trigger: 'blur',
          },
          {
            min: 1,
            max: 50,
            message: '最长允许输入32个字',
            trigger: 'blur',
          },
        ],
        areaId: [
          {
            required: true,
            validator: checkArea,
            // message: "请选择管辖区域",
            trigger: 'change',
          },
        ],
        type: [
          {
            required: true,
            message: '请选择用户类型',
            trigger: 'change',
          },
        ],
        industryId: [
          {
            required: true,
            validator: checkIndustryId,
            // message: "请选择管辖区域",
            trigger: 'change',
          },
        ],
      },
      roleList: [],
      role: [],
      // 设置角色弹窗
      roluFormVisible: false,
      roluFormData: {
        role: '',
        id: '',
      },
      roluFormRules: {
        role: [
          {
            required: true,
            validator: checkRole,
            trigger: 'change',
          },
        ],
      },
      // 用户弹窗loading
      isUserLoading: false,
      // 角色弹窗loading
      isRuleLoading: false,
      loading: true,
      isShow: false,
      //按钮权限
      //修改
      hasUserUpdate: true,
      //分配角色
      hasUserroleUpdate: false,
      //启用，禁用
      hasUserstatusUpdate: false,
      typeData: [],
      industryData: [],
    }
  },
  computed: { ...mapState(['areasOptions']) },

  created() {
    this.$nextTick(function () {
      this.$refs.pagination.getTableListData()
    })
    this.getAreas({ areaId: this.$store.state.areaInfoArr.areaId })
    this.getTypeList()
    this.getIndustryList()
    // 判断按钮权限
    // this.hasUserUpdate = this.$store.state.buttonLimitsArr.indexOf('userManage:update')>-1;
    this.hasUserroleUpdate =
      this.$store.state.buttonLimitsArr.indexOf('userManage:update') > -1
    this.hasUserstatusUpdate =
      this.$store.state.buttonLimitsArr.indexOf('userManage:update') > -1
  },
  methods: {
    ...mapActions(['getAreas']),

    getTableList(data) {
      this.tableData = data
      this.loading = false
      if (this.tableData.length < 1) {
        this.isShow = true
      }
    },
    //状态判断
    formatState: function (row, column, cellValue) {
      if (cellValue == true) {
        return '启用'
      } else if (cellValue == false) {
        return '禁用'
      }
    },
    //列表查询
    searchTable() {
      this.$refs.pagination.getTableListData()
    },
    //区域选择
    handleChange(item) {},
    // 添加账号
    addAccount() {
      this.formVisible = true
      this.addOrEdit = 0
      this.areaId = []
      this.formData = {
        nickname: '',
        tel: '',
        username: '',
        deptmentName: '',
        areaId: '',
        industryId: '',
        type: '',
      }
    },
    closeDialog() {},
    // 修改账号
    handleEdit(index, row) {
      this.formVisible = true
      this.addOrEdit = 1
      // this.areaId = row.areaId;
      // this.areaId = ["150203"];
      // this.formData = Object.assign({}, row);
      // this.id = row.id;
      this.formData = {
        nickname: row.nickname,
        tel: row.phone,
        username: row.username,
        deptmentName: row.deptmentName,
        areaId: row.areaId,
        id: row.id,
        industryId: row.industryId,
        type: row.type,
      }
      this.getUserdetail(row)
    },
    getUserdetail(row) {
      this.axios({
        method: 'post',
        url: 'api-u/users/userdetail',
        data: {
          id: row.id,
        },
      })
        .then(
          (response) => {
            if (!response.data.hasError) {
              this.areaId = response.data.result.areaIds
              //  this.areaId = response.data.result.areaId;
            } else {
              this.$message({
                message: response.data.errorMsg,
                type: 'error',
              })
            }
          },
          (response) => {
            this.$message({
              message: '数据请求失败，请重试',
              type: 'error',
            })
          }
        )
        .catch((error) => {})
    },
    // 关闭弹窗
    handleClose() {
      this.formVisible = false
      this.$refs['formData'].resetFields()
    },
    handleCloseRules() {
      this.formVisible = false
      this.$refs['formData'].resetFields()
    },
    toAddSubmit() {
      this.$refs.formData.validate((valid) => {
        if (valid) {
          this.addSubmit()
        } else {
        }
      })
    },
    addSubmit() {
      this.formData.areaId = this.areaId[this.areaId.length - 1]
      var data = this.formData
      var url = ''
      var text = ''
      // console.log(this.addOrEdit)
      if (this.addOrEdit === 1) {
        url = 'api-u/users/modifyuser'
        text = '修改成功'
      } else {
        url = 'api-u/users/adduser'
        text = '添加成功'
      }
      this.isUserLoading = true
      this.axios({
        method: 'post',
        url: url,
        data: data,
      })
        .then(
          (response) => {
            this.isUserLoading = false
            if (!response.data.hasError) {
              this.$message({
                message: text,
                type: 'success',
              })
              this.formVisible = false
              this.$refs.pagination.getTableListData()
            } else {
              this.$message({
                message: response.data.errorMsg,
                type: 'error',
              })
            }
          },
          (response) => {
            this.isUserLoading = false
            this.$message({
              message: '数据请求失败，请重试',
              type: 'error',
            })
          }
        )
        .catch((error) => {
          this.isUserLoading = false
        })
    },
    toForbidRow(index, row) {
      var text = ''
      var title = ''
      if (row.enabled == true) {
        text = '是否确认禁用账号?'
        title = '禁用账号'
      } else {
        text = '是否确认启用账号?'
        title = '启用账号'
      }
      this.$confirm(text, title, {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      })
        .then(() => {
          this.forbidRow(index, row)
        })
        .catch(() => {})
    },
    forbidRow(index, row) {
      // if()
      this.axios({
        method: 'post',
        url: 'api-u/users/upateenabled',
        data: {
          id: row.id,
          enabled: !row.enabled,
        },
      })
        .then(
          (response) => {
            if (!response.data.hasError) {
              var text = ''
              if (row.enabled == true) {
                text = '禁用成功'
              } else {
                text = '启用成功'
              }
              this.$message({
                message: text,
                type: 'success',
              })
              this.$refs.pagination.getTableListData()
            } else {
              this.$message({
                message: response.data.errorMsg,
                type: 'error',
              })
            }
          },
          (response) => {
            this.$message({
              message: '数据请求失败，请重试',
              type: 'error',
            })
          }
        )
        .catch((error) => {})
    },
    //角色选中
    assigningRoles(index, row) {
      this.getRoleList(index, row)
    },
    getRoleList(index, row) {
      this.axios({
        method: 'post',
        url: 'api-u/users/roles',
        data: {
          userId: row.id,
        },
      })
        .then(
          (response) => {
            if (!response.data.hasError) {
              this.roluFormVisible = true
              this.roleList = []
              this.role = []
              this.roleList = response.data.result
              this.roluFormData = {
                id: row.id,
              }
              for (var i = 0; i < this.roleList.length; i++) {
                if (this.roleList[i].isCheck == 'true') {
                  this.role.push(this.roleList[i].id)
                }
              }
            } else {
              this.$message({
                message: response.data.errorMsg,
                type: 'error',
              })
            }
          },
          (response) => {
            this.$message({
              message: '数据请求失败，请重试',
              type: 'error',
            })
          }
        )
        .catch((error) => {})
    },
    //选择角色
    handleChecked() {},
    // 关闭分配角色弹窗
    closeRoluDialog() {
      // this.id = "";
      this.roluFormVisible = false
      this.$refs['roluFormData'].resetFields()
    },
    // 点击保存角色
    toSaveRolu() {
      this.$refs.roluFormData.validate((valid) => {
        if (valid) {
          this.saveRolu()
        } else {
        }
      })
    },
    // 确认保存角色
    saveRolu() {
      this.roluFormData.roleIds = JSON.stringify(this.role)
      this.isRuleLoading = true
      this.axios({
        method: 'post',
        url: 'api-u/users/saveroles',
        data: this.roluFormData,
      })
        .then(
          (response) => {
            if (!response.data.hasError) {
              this.$message({
                message: '修改角色成功',
                type: 'success',
              })
              this.roluFormVisible = false
              this.isRuleLoading = false
              this.$refs.pagination.getTableListData()
            } else {
              this.isRuleLoading = false
              this.$message({
                message: response.data.errorMsg,
                type: 'error',
              })
            }
          },
          (response) => {
            this.isRuleLoading = false
            this.$message({
              message: '数据请求失败，请重试',
              type: 'error',
            })
          }
        )
        .catch((error) => {
          this.isRuleLoading = false
        })
    },
    getTypeList() {
      this.axios({
        method: 'get',
        url: 'api-u/users/types',
      })
        .then(
          (response) => {
            if (!response.data.hasError) {
              this.typeData = response.data.result
            } else {
            }
          },
          (response) => {}
        )
        .catch((error) => {})
    },
    getIndustryList() {
      this.axios({
        method: 'post',
        data: { type: 'INDUSTRY' },
        url: 'api-bs/base/dicitem/findbytype',
      })
        .then(
          (response) => {
            if (!response.data.hasError) {
              this.industryData = response.data.result
            } else {
            }
          },
          (response) => {}
        )
        .catch((error) => {})
    },
  },
}
</script>

<style scoped lang="less">
.el-button--primary {
  color: #fff;
  background: #009588;
  border-color: #009588;
}
.container {
  position: absolute;
  top: 130px;
  left: 24px;
  right: 24px;
  bottom: 24px;
  background: #fff;
  overflow: hidden;
  .titleBoxOut {
    padding: 0 24px;
    background: #fff;
  }
  .titleBox {
    border-bottom: 1px solid #e3e7e9;
    padding: 14px 0;
    margin-bottom: 0px;
    position: relative;
    .listAddBtn {
      position: absolute;
      right: 16px;
      top: 8px;
      width: 136px;
      line-height: 34px;
      height: 34px;
      padding: 0;
      background: #009588;
      border: none;
    }

    .blockTitle {
      font-weight: bold;
      font-size: 18px;
      color: #333;
      line-height: 22px;
    }
  }
  .centerSection {
    padding: 24px;
    position: absolute;
    overflow-y: auto;
    left: 0;
    bottom: 0;
    right: 0;
    top: 68px;
  }
}
@media screen and (min-width: 1280px) and (max-width: 1366px) {
  .searchInputWidth /deep/.el-form-item__label {
    width: 56px;
  }
}

.brand-dialog-min-width .el-select {
  width: 100%;
}
</style>
